package com.atguigu.spzx.product.service.impl;

import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper , Category> implements CategoryService {
    @Cacheable(value = "spzx:cates" , key = "'tree'" , unless = "#result.size()==0")
    @Override
    public List<Category> getCategoryTree() {
        //1、查询所有分类
        List<Category> categories = baseMapper.selectList(null);
        //2、组装数据
        List<Category> levelOneCates = categories.stream().filter(category -> category.getParentId().longValue() == 0l)
                .collect(Collectors.toList());
        buildCatesTree(levelOneCates , categories);
        return levelOneCates;
    }

    private void buildCatesTree(List<Category> parents, List<Category> categories) {
        if(CollectionUtils.isEmpty(parents)){
            return;
        }
        parents.forEach(parent->{
            List<Category> children = categories.stream()
                    .filter(category -> category.getParentId().longValue() == parent.getId().longValue())
                    .collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(children)){
                parent.setHasChildren(true);
                parent.setChildren(children);
                buildCatesTree(children , categories);
            }
        });

    }
}
